import Cookies from 'js-cookie'
import domtoimage from 'dom-to-image'
import CONSTANTS from '@/config/constants'
import util from '@/libs/util'
import mixin from '../mixin'
import DragDropContainer from '@/views/prizemodel/dragDropContainer/dragDropContainer.vue'

export default {
    props: ['baseuser', 'themeId', 'themeName', 'template'],
    mixins: [mixin],
    components: { DragDropContainer },
    data() {
        return {
            SERVER_HOST: CONSTANTS.SERVER_HOST,

            makeTemplate: {
                backgroundUrl: '',
                sprites: []
            },
            allMember: [],
            formData: {
                perNum: 1
            }
        }
    },
    mounted() {
        this.showLoading()

        this.makeTemplate = JSON.parse(this.template.content);
        this.loadMembers()

        this.formData.themeid = this.themeId
        this.formData.modelid = this.template.id

        this.$nextTick(() => {
            const rect = this.$el.querySelector('.dnd-container').getBoundingClientRect();
            this.$refs.dndContainer.applyContainerSize(rect.width, 600)
        })

        this.$Spin.hide()
    },
    methods: {
        async loadMembers() {
            util.ajax.post(CONSTANTS.GET_MEMBER_BY_THEME, util.toFormData({
                themeId: this.themeId
            })).then(res => {
                let data = res.data.data.list;
                data.forEach((item) => {
                    this.allMember.push({
                        key: item.id,
                        label: item.member.realname + '-' + item.member.phone,
                        name: item.team ? item.team : item.member.realname,
                        memberId: item.memberId,
                        spare1: item.spare1,
                        spare2: item.spare2,
                        spare3: item.spare3,
                        diplomasId: item.diplomasId,
                        diplomas: item.diplomas.name,
                        school: item.member.school
                    });
                });
            });
        },
        replaceText(name, text) {
            let currSprite = this.makeTemplate.sprites;
            var objE = document.createElement('div');
            currSprite.forEach((item, index) => {
                if (item.name === name) {
                    objE.innerHTML = item.content;
                    objE.getElementsByTagName('span')[0].innerHTML = text;
                    this.$refs.dndContainer.updateSpriteTextByName(item.name, objE.innerHTML)
                }
            });
        },
        doGenerate() {
            if (this.allMember.length === 0) {
                this.$Modal.error({
                    content: '该主题下没有会员！'
                });
                return;
            }
            this.$Spin.show({
                render: (h) => {
                    return h('div', [
                        h('Icon', {
                            'class': 'demo-spin-icon-load',
                            props: {
                                type: 'load-c',
                                size: 30
                            }
                        }),
                        h('div', '奖状生成中请稍等...')
                    ]);
                }
            });
            this.replaceText('theme', this.themeName);
            this.makePrize(this.allMember[0], 0);
        },
        makePrize(item, index) {
            let sprites = this.makeTemplate.sprites;
            let image = this.$refs.dndContainer.$image;
            let formData = this.formData;
            formData.membeid = item.memberId;
            formData.diplomasid = item.diplomasId;
            formData.orgid = this.baseuser.orgId;
            let haveQRcode = false;
            sprites.forEach((citem) => {
                if (citem.name && citem.name === 'QRcode') {
                    haveQRcode = true;
                }
            });
            util.ajax.post('/busine/prizes/save', util.toFormData(formData)).then(res => {
                let prizeId = res.data.data;
                var objE = document.createElement('div');
                if (haveQRcode) {
                    util.ajax.post('/qRcode/qRcode', util.toFormData({
                        prizeId: prizeId
                    })).then((qrRes) => {
                        if (qrRes.data.message === 'SUCCESS') {
                            let QRcode = qrRes.data.data;
                            sprites.forEach((citem, index) => {
                                objE.innerHTML = citem.content;
                                if (citem.name && citem.name === 'name') {
                                    var perNum = this.formData.perNum;
                                    var nameList = item.name.split('、');
                                    var name = '';
                                    for (var i = 0; i < nameList.length; i++) {
                                        if (i > 0) {
                                            if (i % perNum === 0) {
                                                name += '<br>';
                                            } else {
                                                name += '、';
                                            }
                                        }
                                        name += nameList[i];
                                    }
                                    objE.getElementsByTagName('span')[0].innerHTML = name;
                                    this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML);
                                } else if (citem.name && citem.name === 'QRcode') {
                                    citem.imageSrc = this.SERVER_HOST + QRcode;
                                } else if (citem.name && citem.name !== 'theme') {
                                    objE.getElementsByTagName('span')[0].innerHTML = item[citem.name];
                                    this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML);                                    // citem.text = item[citem.name];
                                }
                            });
                            this.toPicture(image, index, prizeId);
                        } else {
                            this.$Message.warning(qrRes.data.message || '未知错误！');
                            util.ajax.post('/busine/prizes/delete', util.toFormData({
                                id: prizeId
                            }));
                        }
                    });
                } else {
                    sprites.forEach((citem) => {
                        objE.innerHTML = citem.content;
                        if (citem.name && citem.name === 'name') {
                            var perNum = this.formData.perNum;
                            var nameList = item.name.split('、');
                            var name = '';
                            for (var i = 0; i < nameList.length; i++) {
                                if (i > 0) {
                                    if (i % perNum === 0) {
                                        name += '<br>';
                                    } else {
                                        name += '、';
                                    }
                                }
                                name += nameList[i];
                            }
                            objE.getElementsByTagName('span')[0].innerHTML = name;
                            this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML)
                        } else if (citem.name && citem.name !== 'theme') {
                            objE.getElementsByTagName('span')[0].innerHTML = item[citem.name];
                            this.$refs.dndContainer.updateSpriteTextByName(citem.name, objE.innerHTML)
                        }
                    });
                    this.toPicture(image, index, prizeId);
                }
            });
        },
        toPicture(image, index, prizeId) {
            this.$nextTick().then(() => {
                const done = this.$refs.dndContainer.capture()
                domtoimage.toPng(image, {
                    quality: 1
                }).then((dataUrl) => {
                    done()
                    util.ajax.post('/upload/uploadPrize', util.toFormData({
                        dataUrl: dataUrl
                    })).then(imgRes => {
                        if (imgRes.data.message === 'SUCCESS') {
                            util.ajax.post('/busine/prizes/save', util.toFormData({
                                id: prizeId,
                                imgpath: imgRes.data.data.imgPath
                            })).then(() => {
                                if (index + 1 >= this.allMember.length) {
                                    this.$Message.success('奖状生成完成！');
                                    this.$Spin.hide();
                                    this.$emit('generate-complete')
                                } else {
                                    this.makePrize(this.allMember[index + 1], index + 1);
                                }
                            });
                        } else {
                            this.$Message.warning(imgRes.data.message || '未知错误！');
                            util.ajax.post('/busine/prizes/delete', util.toFormData({
                                id: prizeId
                            }));
                        }
                    });
                });
            });
        }
    },
    computed: {
    },
    beforeDestroy() {
    }
};